package com.cloudcc.mobile.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.MessageNumX;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dao.impl.ApprovalEngineImpl;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.db.PushSaveMessageDB;
import com.cloudcc.mobile.entity.Message;
import com.cloudcc.mobile.entity.PushSaveMessage;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.ConfigManager;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.messagecent.BeauTongzhi;
import com.cloudcc.mobile.messagecent.TongzhiImpl;
import com.cloudcc.mobile.util.ToastUtil;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.MessageActivity;
import com.cloudcc.mobile.view.activity.TaskManagementActivty;
import com.cloudcc.mobile.view.dynamic.DynamicActivity;
import com.cloudcc.mobile.view.mymodel.ParseJson;
import com.cloudcc.mobile.view.mymodel.my;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mypage.model.MainApproNum;
import com.mypage.view.activity.ApprovalPendingActivity;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageService;
import com.umeng.message.common.UmLog;
import com.umeng.message.entity.UMessage;

import org.android.agoo.common.AgooConstants;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lin on 2017/7/27.
 */

public class MyPushIntentService extends UmengMessageService implements IEventLife {
    private static final String TAG = MyPushIntentService.class.getName();

    NotificationManager manager;
    ToastUtil toast;
    Handler handler;
    String reminderText;
    private TongzhiImpl tongzhiImpl = new TongzhiImpl();
    private BeauEventList.BeauTongzhiEvent event;

    String contentText;
    String relatedId;
    //声音提醒
    boolean isMusic;//音乐
    boolean isVibrate;

    @Override
    public void onMessage(Context context, Intent intent) {
        try {

            //可以通过MESSAGE_BODY取得消息体
            String message = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
            UMessage msg = new UMessage(new JSONObject(message));
            UmLog.d(TAG, "message=" + message);      //消息体
            UmLog.d(TAG, "custom=" + msg.custom);    //自定义消息的内容
            UmLog.d(TAG, "title=" + msg.title);      //通知标题
            UmLog.d(TAG, "text=" + msg.text);        //通知内容
            // code  to handle message here
            // ...

            //解析通知信息
            JSONObject extra = new JSONObject(message).optJSONObject("extra");
            String function = extra.optString("function");
            relatedId = extra.optString("relatedId");
            contentText = msg.title;
            reminderText = extra.optString("reminderText");
            String messageType = extra.optString("messageType");
            String userid = extra.optString("userid");

            if (userid != null && !userid.equals(UserManager.getManager().getUser().userId)) {//如果不是当前用户的推送，直接返回
                return;
            }

            //声音提醒
            isMusic = ConfigManager.getInstance().isAllowPushSound();//音乐
            isVibrate = ConfigManager.getInstance().isAllowPushVibrate();//震动
            manager = (NotificationManager) getSystemService(context.NOTIFICATION_SERVICE);

            //通知提醒
            if (messageType.equals("message")) {
                Intent intent1 = new Intent(this, MessageActivity.class);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                notifacation("", intent1, contentText);
            }
            if (messageType.equals("notification")) {
                messageNum();
                if (function.equals("approval")) {// 审批通知
                    handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            initTongzhi(relatedId);
                        }
                    });
//                    Intent intent1 = new Intent(this, TaskManagementActivty.class);
//                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    notifacation("", intent1, contentText);
                    EventEngine.post(new MainApproNum());
                }
                if (function.equals("eventAlert")) {// 事件
                    tiXing(isMusic, isVibrate);
                    Intent intent1 = new Intent(this, BeauInfoActivity.class);
                    intent1.putExtra("web.url", UrlManager.getRootUrl() + UrlTools.getObjectUrl_z(relatedId));
                    intent1.putExtra("web", relatedId);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    notifacation("", intent1, contentText);
                }
                if (function.equals("taskAlert")) {// 任务
                    tiXing(isMusic, isVibrate);
                    Intent intent1 = new Intent(this, BeauInfoActivity.class);
                    intent1.putExtra("web.url", UrlManager.getRootUrl() + UrlTools.getObjectUrl_z(relatedId));
                    intent1.putExtra("web", relatedId);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    notifacation("", intent1, contentText);
                }
                if (function.equals("showmsg")) {// 云帖
                    tiXing(isMusic, isVibrate);
                    Intent intent1 = new Intent(this, DynamicActivity.class);
                    intent1.putExtra("chatId", relatedId);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    notifacation("", intent1, contentText);
                }
            }


            if (reminderText != null && !TextUtils.isEmpty(reminderText) && messageType.equals("notification") && !function.equals("approval")) {
                handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        toast = new ToastUtil(getApplicationContext());
                        toast.setTextNoImage(reminderText).Short(getApplicationContext(), "").show(30, getApplicationContext());
                    }
                });
            }

            //数据库操作
            if (messageType.equals("message")) {// 系统消息
                Message message1 = new Message();
                message1.setContext(contentText);
                message1.setTime(Tools.getTime(System
                        .currentTimeMillis()));
                message1.setIsNew("1");
                MessageDB dbMess = new MessageDB(context, UserManager
                        .getManager().getUser().userId + "message");
                dbMess.saveMessage(message1);
            }
            if (messageType.equals("notification")) {//通知中心

                PushSaveMessageDB db;//将通知装进本地数据库
                if (userid != null && !userid.equals(UserManager.getManager().getUser().userId)) {//如果不是当前用户的推送，存储到推送用户的通知中心
                    db = new PushSaveMessageDB(this, userid + "pushsavemessage");
                } else {
                    db = new PushSaveMessageDB(this, UserManager
                            .getManager().getUser().userId + "pushsavemessage");
                }
                PushSaveMessage mes = new PushSaveMessage();
                mes.setRelatedId(relatedId);
                mes.setTimes(Tools.getTime3(System
                        .currentTimeMillis()));
                mes.setContentText(contentText);
                mes.setReminderText(reminderText);
                mes.setFunction(function);
                mes.setIsNew("1");//未读
                db.savePushSaveMessage(mes);

                //消息数
                long b = 0;
                if (db.isExit()) {
                    b = db.getNewPushSaveMessageNum();
                }
//                EventEngine.post(new MessageNumX(b));
//                RunTimeManager.getInstance().setMessageNx(b);

            }


            // 对完全自定义消息的处理方式，点击或者忽略
            boolean isClickOrDismissed = true;
            if (isClickOrDismissed) {
                //完全自定义消息的点击统计
                UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
            } else {
                //完全自定义消息的忽略统计
                UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
            }

            // 使用完全自定义消息来开启应用服务进程的示例代码
            // 首先需要设置完全自定义消息处理方式
            // mPushAgent.setPushIntentServiceClass(MyPushIntentService.class);
            // code to handle to start/stop service for app process
//            JSONObject json = new JSONObject(msg.custom);
//            String topic = json.getString("topic");
//            UmLog.d(TAG, "topic=" + topic);
//            if (topic != null && topic.equals("appName:startService")) {
//                // 在【友盟+】portal上新建自定义消息，自定义消息文本如下
//                //{"topic":"appName:startService"}
////                if (Helper.isServiceRunning(context, NotificationService.class.getName()))
////                    return;
////                Intent intent1 = new Intent();
////                intent1.setClass(context, NotificationService.class);
////                context.startService(intent1);
//            } else if (topic != null && topic.equals("appName:stopService")) {
//                // 在【友盟+】portal上新建自定义消息，自定义消息文本如下
//                //{"topic":"appName:stopService"}
////                if (!Helper.isServiceRunning(context,NotificationService.class.getName()))
////                    return;
////                Intent intent1 = new Intent();
////                intent1.setClass(context, NotificationService.class);
////                context.stopService(intent1);
//            }
        } catch (Exception e) {
            UmLog.e(TAG, e.getMessage());
        }
    }


    /**
     * 是否提醒
     *
     * @param isZhengdong
     * @param isMusic
     */
    private void tiXing(boolean isZhengdong, boolean isMusic) {
        if (isZhengdong) {// 震动提醒
            Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
            long[] pattern = {1000, 1000, 1000, 1000, 1000}; // OFF/ON/OFF/ON...
            vibrator.vibrate(pattern, -1);
        }
        if (isMusic) {// 声音提醒
            LogUtils.d("app", "声音提示参数：" + isMusic);
            MediaPlayer music = MediaPlayer.create(this, R.raw.cloudcc);
            music.start();
        }
    }

    public void notifacation(String name, Intent myintent,
                             String showmsg) {

        PendingIntent contentIntent = PendingIntent.getActivity(this, 1,
                myintent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(
                this)
                .setSmallIcon(R.drawable.icon)
                .setContentTitle(name)
                .setContentText(showmsg)
                .setTicker("亲，来消息了")
                .setAutoCancel(true)
                .setContentIntent(contentIntent)
                .setDefaults(Notification.DEFAULT_LIGHTS);

        // 发送通知
        manager.notify(1000, builder.build());
    }

    private void messageNum() {
        event = new BeauEventList.BeauTongzhiEvent();
        tongzhiImpl.tongzhiDate(event);
    }

    public void onEventMainThread(BeauEventList.BeauTongzhiEvent event) {
        if (event.isError()) {
            return;
        }
        List<BeauTongzhi> tongzhiLi = event.getData();
        long a = 0;
        for (int i = 0; i < tongzhiLi.size(); i++) {
            if ("0".equals(tongzhiLi.get(i).status)) {
                a++;
            }
        }
        RunTimeManager.getInstance().setMessageNx(a);
        EventEngine.post(new MessageNumX(a));
    }

    @Override
    public void onStart(@Nullable Intent intent, int startId) {
        super.onStart(intent, startId);
        messageNum();

    }

    private my model;
    private ApprovalEngineImpl engine = new ApprovalEngineImpl();

    public void initTongzhi(String recordId) {
        engine.GetManagementTask_z(RunTimeManager.getInstance().getUserId(), 1, recordId, new ResultCallBack<JsonObject>() {
            @Override
            public void onSuccess(JsonObject t) {
                Gson gson = new Gson();
                ParseJson json = gson.fromJson(t, ParseJson.class);
                List<ParseJson.Zu> list = new ArrayList<ParseJson.Zu>();
                list = json.resultList;
                tiXing(isMusic, isVibrate);//小心提醒
                toast = new ToastUtil(getApplicationContext());//浮层弹窗
                toast.setTextNoImage(reminderText).Short(getApplicationContext(), "").show(30, getApplicationContext());
                if (list.size() > 0) {
                    tiXing(isMusic, isVibrate);
                    model = list.get(0).data.get(0);
                    Intent intent1 = new Intent(MyPushIntentService.this, ApprovalPendingActivity.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("extra", model);
                    intent1.putExtras(bundle);
                    notifacation("", intent1, contentText);
                } else {
                    Intent intent1 = new Intent(MyPushIntentService.this, TaskManagementActivty.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    notifacation("", intent1, contentText);
                }
            }

            @Override
            public void onFailure(ErrorInfo error) {
            }
        });
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegister();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        register();
    }
}
